package jmind.core.image.ocr;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import jmind.base.util.DataUtil;
import jp.sourceforge.qrcode.QRCodeDecoder;

import com.swetake.util.Qrcode;

/**
 * jp qrcode 二维码的使用（生成和解析）
 * http://duanjiangong.iteye.com/blog/962269
 * @author weibo-xie
 * 2012-8-7
 */
public class QRCodeImg {

    public static void main(String[] args) {
        try {
            String decode = decode("d:/data/2901.jpg");
            System.out.println(decode);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void encode(String content, String FilePath) throws Exception {
        Qrcode qrcode = new Qrcode();

        qrcode.setQrcodeErrorCorrect('M');
        qrcode.setQrcodeEncodeMode('B');
        qrcode.setQrcodeVersion(7);
        byte[] d = content.getBytes("GBK");
        BufferedImage bi = new BufferedImage(139, 139, BufferedImage.TYPE_INT_RGB);
        // createGraphics
        Graphics2D g = bi.createGraphics();
        // set background
        g.setBackground(Color.WHITE);
        g.clearRect(0, 0, 139, 139);
        g.setColor(Color.BLACK);
        if (d.length > 0 && d.length < 123) {
            boolean[][] b = qrcode.calQrcode(d);
            for (int i = 0; i < b.length; i++) {
                for (int j = 0; j < b.length; j++) {
                    if (b[j][i]) {
                        g.fillRect(j * 3 + 2, i * 3 + 2, 3, 3);
                    }
                }
            }
        }
        g.dispose();
        bi.flush();
        File f = new File(FilePath);
        ImageIO.write(bi, "png", f);
    }

    public static String decode(String filePath) {
        QRCodeDecoder decoder = new QRCodeDecoder();
        File imageFile = new File(filePath);
        BufferedImage image = null;
        try {
            image = ImageIO.read(imageFile);
            String decodedData = new String(decoder.decode(new J2SEImage(image)), "GBK");
            return decodedData;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return DataUtil.EMPTY;
    }
}
